package com.example.play.view

import android.view.View
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.example.base.app.RouterPath
import com.example.common.entity.MovieVideoEntity
import com.example.common.entity.SimpleVideoEntity
import com.example.common.event.CustomEvent
import com.example.common.mvi.BaseMviFragment
import com.example.image.GlideUtils
import com.example.image.glide.GlideImgLoader
import com.example.play.R
import com.example.play.adapter.MovieVideoListAdapter
import com.example.play.adapter.SimpleVideoListAdapter
import com.example.play.adapter.SimpleVideoListAdapter.ItemClickListener
import com.example.play.databinding.FragmentPlayBinding
import com.example.play.entity.AuthorEntity
import com.example.play.intent.PlayViewIntent
import com.example.play.state.PlayUiState
import com.example.play.vm.PlayViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collectLatest
import org.greenrobot.eventbus.EventBus

@Route(path = RouterPath.PATH_INTRODUCE_PAGE)
@AndroidEntryPoint
class PlayFragment : BaseMviFragment<FragmentPlayBinding>() {
    @Autowired
    @JvmField var userId:String=""
    @Autowired
    @JvmField var moduleType:Int=0
    @Autowired
    @JvmField var videoTypeId:Int=-1//推荐
    @Autowired
    @JvmField var channelId:String=""

    private var pageIndex=1
    private var pageSize=10

    private lateinit var simpleVideoListAdapter: SimpleVideoListAdapter
    private lateinit var movieVideoListAdapter: MovieVideoListAdapter

    private val simpleVideoEntity= mutableListOf<SimpleVideoEntity>()
    private val movieVideoEntity= mutableListOf<MovieVideoEntity>()

    private val mViewModel:PlayViewModel by activityViewModels ()

    override fun getLayoutId(): Int = R.layout.fragment_play

    override fun initViews() {
        ARouter.getInstance().inject(this)

        simpleVideoListAdapter=SimpleVideoListAdapter(simpleVideoEntity).apply {
            setOnItemClickListener(object : ItemClickListener {
                override fun onItemChildClick(v: View, position: Int, entity: SimpleVideoEntity) {
                    //使用EventBus给外部Activity发送事件（方案一）
                    EventBus.getDefault().post(CustomEvent("PlayActivity",entity,0))
                    //使用LiveDataBus发送事件（方案二）
                }
            })
        }
        movieVideoListAdapter=MovieVideoListAdapter(movieVideoEntity).apply {
           setOnItemClickListener(object : MovieVideoListAdapter.ItemClickListener {
               override fun onItemChildClick(v: View, position: Int, entity: MovieVideoEntity) {
                   //使用EventBus给外部Activity发送事件（方案一）
                   EventBus.getDefault().post(CustomEvent("PlayActivity",entity,1))
                   //使用LiveDataBus发送事件（方案二）
               }

           })
        }
        mDataBinding.rvUserVideo.apply {
            layoutManager= LinearLayoutManager(requireContext(),LinearLayoutManager.VERTICAL,false)
            if (moduleType == 0){
                mDataBinding.rvUserVideo.adapter = simpleVideoListAdapter
            }else{
                mDataBinding.rvUserVideo.adapter = movieVideoListAdapter
            }
        }

    }

    override suspend fun sendViewIntent() {
        super.sendViewIntent()
        //获取作者信息
        mViewModel.channel.send(PlayViewIntent.LoadAuthorById(userId))
        //加载视频列表
        when (moduleType){
            0->{
                if (videoTypeId==-1){
                    mViewModel.channel.send(PlayViewIntent.LoadRecommendSimpleVideo(pageIndex,pageSize))
                }else{
                    mViewModel.channel.send(PlayViewIntent.LoadSimpleVideoByChannelId(channelId,pageIndex,pageSize))
                }
            }
            1->{
                if (videoTypeId==-1){
                    mViewModel.channel.send(PlayViewIntent.LoadRecommendMutilVideo(pageIndex,pageSize))
                }else{
                    mViewModel.channel.send(PlayViewIntent.LoadMutilVideoByTypeId(videoTypeId,pageIndex,pageSize))
                }
            }
        }
    }

    override suspend fun collectUIState() {
        super.collectUIState()
        mViewModel.uiStateFlow.collectLatest {
            when(it){
                is PlayUiState.LoadAuthorByIdSuccess-> updateAuthorById(it.list)
                is PlayUiState.LoadRecommendSimpleVideoSuccess-> updateRecommendSimpleVideo(it.list)
                is PlayUiState.LoadRecommendMutilVideoSuccess-> updateRecommendMutilVideo(it.list)
                else->{}
            }
        }
    }



    private fun updateAuthorById(entity: AuthorEntity) {
        GlideUtils.loadCircleImage(requireContext(),entity.avatar_url,mDataBinding.ivUserIcon)
        mDataBinding.apply {
            tvUserName.text=entity.name
            tvUserDesc.text=entity.author_desc
            tvLikeCount.text=entity.followerscount.toString()
            tvSendTime.text=entity.ctime
        }
    }
    private fun updateRecommendSimpleVideo(list: List<SimpleVideoEntity>) {
        if (pageIndex ==1){
            simpleVideoEntity.clear()
        }
        simpleVideoEntity.addAll(list)
        simpleVideoListAdapter.notifyDataSetChanged()
    }

    private fun updateRecommendMutilVideo(list: List<MovieVideoEntity>) {
        if (pageIndex ==1){
            movieVideoEntity.clear()
        }
        movieVideoEntity.addAll(list)
        movieVideoListAdapter.notifyDataSetChanged()
    }
}